/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package trunk.model;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket; 
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author Karine
 */
public class ProgramCliente {

	private ObjectOutputStream output;//cria fluxo de entrada
	private ObjectInputStream input;//cria fluxo de saída
	private Socket conexaoCliente;//Cria Socket Cliente
	private String endereco;
	private int porta;
	public Semaphore semaforo;

	public ProgramCliente(String endereco, int porta){

		this.endereco = endereco;
		this.porta = porta;
		this.semaforo = new Semaphore(1);
	}//fim do construtor 

	public void criarConexao() throws UnknownHostException, IOException{         

		//Cria Socket para fazer a conexão com o servidor
		conexaoCliente = new Socket(InetAddress.getByName(endereco), porta);

	}


	public  void obterStreams() throws IOException {

		//Configura o fluxo de saída para objetos
		output = new ObjectOutputStream(conexaoCliente.getOutputStream());

		//Configura o fluxo de entrada para objetos
		input = new ObjectInputStream(conexaoCliente.getInputStream());                     
	}   


	public void fecharConexao() throws IOException{
		//fecha os fluxos e o socket
		output.close();
		input.close();
		conexaoCliente.close();
	}        

	public Pacote enviarMsn(Pacote mensagem) throws IOException, ClassNotFoundException{
		try {
			//Envia o Objeto ao Servidor
			semaforo.acquire();//
		} catch (InterruptedException ex) {
			Logger.getLogger(ProgramCliente.class.getName()).log(Level.SEVERE, null, ex);
		}
		output.writeObject(mensagem);
		output.flush();

		// Aguardando servidor responder:
		Pacote pacote = (Pacote) input.readObject(); // Ler a mensagem do servidor
		semaforo.release();//Libera o recurso
		return pacote;      
	}
	//Envia anexo Para o servidor
	public void enviarAnexoServidor(File file) throws IOException{

		FileInputStream in = new FileInputStream(file);

		Socket socket = new Socket(endereco, 5678);

		OutputStream out = socket.getOutputStream();

		OutputStreamWriter osw = new OutputStreamWriter(out);

		BufferedWriter writer = new BufferedWriter(osw);

		writer.write(file.getName() + "\n");

		writer.flush();

		int tamanho = 462312; // buffer de 4KB
		byte[] buffer = new byte[tamanho];
		int lidos = -1;
		int total = 0;
		while ((lidos = in.read(buffer, 0, tamanho)) > 0) {
			out.write(buffer, 0, lidos);
			total = total + lidos;
		}
		out.flush();
		in.close();
		out.close();
		socket.close();
	}

	public void recebeAnexo() throws IOException{

		try {
			ServerSocket server = new ServerSocket(56782);
			Socket clSocket = server.accept();

			InputStream in = clSocket.getInputStream();

			InputStreamReader isr = new InputStreamReader(in);

			BufferedReader reader = new BufferedReader(isr);

			String fName = reader.readLine();

			System.out.println(fName);

			File f1 = new File(fName);

			FileOutputStream out = new FileOutputStream(f1);
			System.out.println(f1.getAbsolutePath());
			int tamanho = 462312; // buffer de 4KB
			byte[] buffer = new byte[tamanho];
			int lidos = -1;                                        
			while ((lidos = in.read(buffer, 0, tamanho)) > 0) {
				out.write(buffer, 0, lidos);
			}
			out.flush();
			in.close();
			out.close();
			server.close();
		} catch (IOException e) {
			e.printStackTrace();
		}


	}

	public void executaClient() throws IOException, ClassNotFoundException, SocketException{
		criarConexao();
		obterStreams();
	}    

	public int getPortaConexao(){
		return conexaoCliente.getLocalPort();
	}

    public Socket getConexaoCliente() {
        return conexaoCliente;
    }

}// Fim da Classe